<?php

namespace App\Controllers\Diary;

use App\Models\Diary\Diary;
use App\Models\Diary\CommentPra;


class GetRecomDiary extends \App\Libs\Base\BaseAction
{
    protected function beforeRun()
    {
        parent::beforeRun();
        //$this->needLogin = TRUE;
    }

    /**
     * @return array 根据传入的周期数(period)，返回可以显示的，按照预设的排序规则排序的日记，
     * 可选参数：page,num
     */
    public function execute()
    {
        $period = $this->request->get('period', 'int', 0);
        if ($period == 0) {
            return \App\Libs\Views\Json::view(0, '缺少参数：period', null);
        }
        $getPage = $this->request->get('page', 'int', 1);
        $finalNum = $this->request->get('num', 'int', 10);
        $offset = ($getPage - 1) * $finalNum;
        $allTopicData = Diary::findAll([
            'conditions' => ' isshow = ?1 and period = ?2',
            'order' => 'order_score desc',
            //日记使用id，进行标识
            'columns' => 'id,editor_name,editor_avatar,diary_logo,diary_name,zan_num,read_num',
            'bind' => array(1 => true, 2 => $period),
            'offset' => $offset,
            'limit' => $finalNum
        ])->toArray();
		
		
        if (empty($allTopicData)) {
            return \App\Libs\Views\Json::view(0, '指定的活动无日记', []);
        } else {
			
				//判断当前用户是否评价了
				$allCommentId = [];
				foreach( $allTopicData as $k=>$v ){
					$allTopicData[$k]['iszan'] = 0;
					$allCommentId[] = $v['id'];
				}
			if( isset( $this->session->user ) ){
				$allTopicData = self::commentUser( $this->session->user->id , $allTopicData , $allCommentId  );
			}
            return \App\Libs\Views\Json::view(0, '成功', $allTopicData);
        }


    }
	
	
	/**
	*	展示当前登录用户所点赞的值
	*/
	public static function commentUser( $uid , $allTopicData , $allCommentId ){
		$commentAll = CommentPra::findAll( array( 
			' did IN ({commentId:array}) and uid = :uid: and show = 1',
			'bind' => array( 'commentId' => $allCommentId , 'uid'=>$uid)
		) )->toArray();
		if( empty( $commentAll ) ){
			return $allTopicData;//不存在点赞，直接返回之前的数据
		}
		foreach( $commentAll as $k=>$v ){
			$allcommentInfo[$v['did']] = $v['did'];
		}
		
		//有点赞
		foreach( $allTopicData as $k=>$v ){
			if( !empty( $allcommentInfo[$v['id']] ) ){
				$allTopicData[$k]['iszan'] = 1;
			}
		}
		return $allTopicData;
	}
}
